﻿using System.Windows;
using Microsoft.Phone.Scheduler;
using System;
using MVBuddy.Common.Helpers;
using MVBuddy.Common.Model;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using System.Linq;

namespace MVBuddy.TaskAgent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            string userName = StorageManager.LoadAppSetting("Username") as string;
            string password = StorageManager.LoadAppSetting("Password") as string;

            HtmlRequest loginRequest = new HtmlRequest(new Uri("http://m.mediavida.com/login.php"), "POST", "application/x-www-form-urlencoded", new System.Collections.Generic.Dictionary<string, string>()
                {
                    { "name", userName },
                    { "password", password },
                });

            loginRequest.HtmlRequestCompleted += loginRequest_HtmlRequestCompleted;
            loginRequest.DoRequest();
        }

        private void loginRequest_HtmlRequestCompleted(object sender, HtmlRequestCompletedEventArgs e)
        {
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                UserData userData = UserDataExtractor.Extract(e.Result);

                if (userData.Logged)
                {
                    if (ShellTile.ActiveTiles.ToList().Count > 1)
                    {
                        ShellTile tile = ShellTile.ActiveTiles.ElementAtOrDefault(1);
                        string tilePath = "/Shared/ShellContent/TileBackBackground.jpg";

                        WriteableBitmap backBitmap = UserDataExtractor.RenderUserDataForBackgroundTile(userData);
                        StorageManager.SaveShellBitmapAsJpeg(tilePath, backBitmap);

                        tile.Update(new StandardTileData()
                        {
                            BackTitle = string.Empty,
                            Count = userData.NotificationCount + userData.FavoriteCount + userData.MessageCount,
                            BackContent = string.Empty,
                            BackBackgroundImage = new Uri("isostore:" + tilePath, UriKind.Absolute),
                        });
                    }
                }
                else
                {
                    // TODO: show message in tile
                }

                NotifyComplete();
            });
        }
    }
}